using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Lesson10 : MonoBehaviour
{
    public Slider sliderX;
    public Slider sliderY;
    public Slider sliderZ;
    public Button btnSetX;
    public Button btnReset;
    public Toggle togEulerAngles;
    public Toggle togQuaternino;
    //是否使用欧拉角旋转
    bool isEulerAngles = true;
    private Quaternion curRotation;
    public Transform airplane;
    private float angleX, angleY, angleZ;
    void Start()
    {
        curRotation = airplane.rotation; // 记录初始旋转
        sliderX.onValueChanged.AddListener((value) =>
        {
            float angle = SliderToAngle(value);
            ApplyRotation(angle, Vector3.right); // X轴
        });
        sliderY.onValueChanged.AddListener((value) =>
        {
            float angle = SliderToAngle(value);
            ApplyRotation(angle, Vector3.up); // Y轴
        });
        sliderZ.onValueChanged.AddListener((value) =>
        {
            float angle = SliderToAngle(value);
            ApplyRotation(angle, Vector3.forward); // Z轴
        });
        btnSetX.onClick.AddListener(() =>
        {
            curRotation = Quaternion.identity;
            airplane.rotation = curRotation;
            sliderX.value = 0.625f;
        });
        togEulerAngles.onValueChanged.AddListener(v => isEulerAngles = v);
        togQuaternino.onValueChanged.AddListener(v => isEulerAngles = !v);
        btnReset.onClick.AddListener(()=>
        {
            sliderX.value = 0.5f;
            sliderY.value = 0.5f;
            sliderZ.value = 0.5f;
            curRotation = Quaternion.identity;
            airplane.rotation = curRotation;
        });
    }

    // 应用旋转(支持欧拉角/四元数)
    private void ApplyRotation(float angle, Vector3 axis)
    {
        if (isEulerAngles)
        {
            // 欧拉角模式（直接设置角度）
            if (axis == Vector3.right) airplane.eulerAngles = new Vector3(angle, airplane.eulerAngles.y, airplane.eulerAngles.z);
            else if (axis == Vector3.up) airplane.eulerAngles = new Vector3(airplane.eulerAngles.x, angle, airplane.eulerAngles.z);
            else if (axis == Vector3.forward) airplane.eulerAngles = new Vector3(airplane.eulerAngles.x, airplane.eulerAngles.y, angle);
        }
        else
        {
            // 四元数模式（增量旋转，避免死锁）
            Quaternion newRot = curRotation * Quaternion.AngleAxis(angle, axis);
            airplane.rotation = newRot;
            curRotation = newRot;
        }
    }

    // 将Slider的value（0-1）映射到角度（-360°~360°）
    private float SliderToAngle(float sliderValue)
    {
        if (sliderValue <= 0.5f)
        {
            // 0~0.5 → -360°~0°
            return Mathf.Lerp(-360f, 0f, sliderValue * 2f);
        }
        else
        {
            // 0.5~1 → 0°~360°
            return Mathf.Lerp(0f, 360f, (sliderValue - 0.5f) * 2f);
        }
    }
}
